package net.asrsmid.sample.adventureanalyzer.service;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.context.Context;

import net.asrsmid.config.AsRsAuthenticator;
import net.asrsmid.connection.AsRsApplicationPool;
import net.asrsmid.invoker.RsWebserviceInvoker;
import net.asrsmid.sample.adventureanalyzer.model.AnalysisContext;
import net.asrsmid.sample.adventureanalyzer.model.AnalysisResult;

public class AdventureAnalyzerRsService extends AdventureAnalyzerService {
	public AdventureAnalyzerRsService(AsRsApplicationPool pool) {
		super(pool);
	}
	
	public AnalysisResult getReport(AnalysisContext ctx) {
		RsWebserviceInvoker invoker = this.getRsWebserviceInvoker();
		
		String reportPath = this.getRsReportPath(ctx.getReportType());
		reportPath = "/AsRsMidSample/QueryEditor/QueryEditorReport";
		Map<String, String> reportParamsMap = new HashMap<String, String> ();
		//reportParamsMap.put("mdxQuery", generateMdxQuery(ctx));
		String deviceInfo = null;
		String reportFormat = "HTML4.0";
		AsRsAuthenticator auth = this.getRsAuthenticator();
		
		byte[] report = invoker.getReport(reportPath, reportParamsMap, reportFormat, deviceInfo, auth);
		
		AnalysisResult result = new AnalysisResult();
		result.setData(report);
		return result;
	}

	public String generateMdxQuery(AnalysisContext ctx) {
		String mdx = null;
		String reportType = ctx.getReportType();
		
		if ("ANALYSIS_TABLE".equalsIgnoreCase(reportType))
			mdx = getAnalysisTableMdxQuery(ctx);
		else if ("TOP10_GRAPHIC".equalsIgnoreCase(reportType))
			mdx = getTop10GraphicMdxQuery(ctx);
		else if ("COMPARISON_GRAPHIC".equalsIgnoreCase(reportType))
			mdx = getComparisonGraphicMdxQuery(ctx);
		return mdx;
	}
	
	private String getAnalysisTableMdxQuery(AnalysisContext ctx) {
		VelocityEngine engine = new VelocityEngine();
		Properties props = new Properties();
		props.put("resource.loader", "class");
		props.put("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
		engine.init(props);
		Template template = engine.getTemplate("analysisTable.vm");
		Context context = new VelocityContext();
		
		context.put("CONTEXT", ctx);
		
		StringWriter writer = new StringWriter();
		template.merge(context, writer);
		return writer.toString();
	}
	
	private String getTop10GraphicMdxQuery(AnalysisContext ctx) {
		return null;
	}
	
	private String getComparisonGraphicMdxQuery(AnalysisContext ctx) {
		return null;
	}
}